package com.yunao.commons.utils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

public class Profile {

	private Properties props;

	public Profile() {
		this("search.properties");
	}

	public Profile(String pathname) {
		try {
			this.props = this.read(pathname);
		} catch (IOException e) {
			throw new IllegalArgumentException(e.getMessage());
		}
	}

	public String getValue(String key) {
		return this.props.getProperty(key);
	}

	public String getValue(String key, String defaultValue) {
		return this.props.getProperty(key, defaultValue);
	}

	public String[] getArrayValue(String key, String separator) {
		if (!this.props.contains(key)) {
			return new String[0];
		}
		String value = this.props.getProperty(key);
		return value.split(separator);
	}

	public int getIntValue(String key) {
		String value = this.props.getProperty(key);
		return Integer.parseInt(value);
	}

	public int getIntValue(String key, int defaultValue) {
		String value = this.props.getProperty(key, String.valueOf(defaultValue));
		return Integer.parseInt(value);
	}

	public Properties props() {
		return this.props;
	}

	private Properties read(String pathname) throws IOException {
		Properties props = new Properties();
		props.load(new FileReader(parseFile(pathname)));
		return props;
	}

	public static File parseFile(String pathname) throws IOException {
		if (new File("conf" + File.separator + pathname).exists()) {
			return new File("conf" + File.separator + pathname);
		}
		if (new File(pathname).exists()) {
			return new File(pathname);
		}
		URL url = Thread.currentThread().getContextClassLoader().getResource("conf" + File.separator + pathname);
		if (url != null) {
			return toFile(url);
		}
		url = Thread.currentThread().getContextClassLoader().getResource(pathname);
		if (url != null) {
			return toFile(url);
		}
		throw new IOException("Configuration miss");
	}

	private static File toFile(URL url) throws IOException {
		try {
			return new File(url.toURI());
		} catch (URISyntaxException e) {
			throw new IOException(e);
		}
	}

}
